from django.shortcuts import render

from django.http import HttpResponse,JsonResponse

from ..models import Types

from django.contrib.auth.decorators import permission_required


# 定义函数
def GetTypesAll():
    # 获取所有的商品分类
    # typelist = Types.objects.all()
    # select *,concat(path,id) as paths from myadmin_types order by paths;
    typelist = Types.objects.extra(select = {'paths':'concat(path,id)'}).order_by('paths')
    for x in typelist:
        # 判断是否为顶级
        if x.pid == 0:
            x.pname = '顶级分类'
        else:
            ob = Types.objects.get(id=x.pid)
            x.pname = ob.name
    # 返回数据
    return typelist

# 添加分类
@permission_required('myadmin.insert_types',raise_exception = True)
def typesadd(request):
    # 分配数据
    context = {'typelist':GetTypesAll()}
    # 加载模板
    return render(request,'myadmin/types/add.html',context)

# 插入分类
@permission_required('myadmin.insert_types',raise_exception = True)
def typesinsert(request):
    try:
        # 接受数据
        data = request.POST.dict()
        data.pop('csrfmiddlewaretoken')
        # 判断当前添加的是否为顶级分类
        if data['pid'] == '0':
            data['path'] = '0,'
        else:
            # 获取父级对象
            ob = Types.objects.get(id=data['pid'])
            # 根据父级的path和我当前选择的pid+',' 进行拼接
            data['path'] = ob.path+data['pid']+','
        # 创建对象
        Types.objects.create(**data)
        # return HttpResponse('hello!')
        # 跳转到列表页
        return HttpResponse('<script>alert("添加成功");location.href="/myadmin/types/index/"</script>')
    except:
        return HttpResponse('<script>alert("添加失败");location.href="/myadmin/types/add/"</script>')

# 分类列表
@permission_required('myadmin.show_types',raise_exception = True)
def typesindex(request):
    
    # type = GetTypesAll()
    typelist=Types.objects.extra(select={'paths':'concat(path,id)'}).order_by('paths')

    # 接受参数 
    types = request.GET.get('types',None)
    keywords = request.GET.get('keywords',None)

    # 判断是否有搜索条件
    if types:
        if types == 'all':
            # 多字段的查询
            # select * from users where username like '%aa%' or age like '%aa%' or
            from django.db.models import Q
            typelist= typelist.filter(Q(id__contains=keywords)|Q(name__contains=keywords)|Q(pid__contains=keywords))
        else:
            data = {types+'__contains':keywords}
            typelist = typelist.filter(**data)
    for x in typelist:
        if x.pid == 0:
            x.pname="顶级分类"
        else:
            ob=Types.objects.get(id=x.pid)
            x.pname=ob.name

    # 数据分页
    from django.core.paginator import Paginator
    # 实例化分页对象,参数1,数据列表  参数2 每页显示的条数
    p = Paginator(typelist, 10)
    # 获取当前的页码数
    page = request.GET.get('page',1)
    # 获取当前页的数据
    typelist = p.page(page)
    # 获取所有的页码列表
    pages = p.page_range

    # 分配数据
    context = {'typelist':typelist}
    # 加载模板
    return render(request,'myadmin/types/index.html',context)


# 执行分类的删除
@permission_required('myadmin.del_types',raise_exception = True)
def typesdelete(request):
    # 接受id,获取对象
    uid=request.GET['id']
    print(uid)
    ob = Types.objects.get(id=uid)
    # 判断当前类下是否还是有子类
    if Types.objects.filter(pid=ob.id).count():
        # 有子类,不能删除
        return JsonResponse({'error':1,'msg':'当前类下有子类不能删除'})
    # 当前类下如果有商品也不能删除
    # return JsonResponse({'error':2,'msg':'当前类下有商品,不能删除'})
    # 没有子类,也没有商品,可以删除,
    ob.delete()  
    return JsonResponse({'error':0,'msg':'删除成功'})

# 分类名的修改
@permission_required('myadmin.edit_types',raise_exception = True)
def typesupdate(request):
    try:
        # 根据id获取对象
        ob = Types.objects.get(id=request.GET['id'])
        print(ob)
        # 修改
        ob.name = request.GET['name']
        ob.save()
        return JsonResponse({'error':0,'msg':'更新成功'})
    except:
        return JsonResponse({'error':1,'msg':'更新失败'})
